package db

import (
	"fmt"
	"fox/config"
	"fox/plugin"
	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlserver"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"sync"
)

type DB struct {
	Db  *gorm.DB
	Dsn string
}

var (
	// GDatabase 单例
	GDatabase *DB
	mu        sync.Mutex
)

func InitDB() (err error) {
	var (
		dsn string
		db  *gorm.DB
	)

	mu.Lock()
	defer mu.Unlock()
	if GDatabase != nil {
		return err
	}

	if config.GConfig.DbDriver == "mysql" {
		dsn = config.GConfig.DbUser + ":" + config.GConfig.DbPassword + "@tcp(" + config.GConfig.DbHost + ":" + config.GConfig.DbPort + ")/" + config.GConfig.DbName + "?charset=utf8mb4"
		if db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
			Logger: logger.Default.LogMode(logger.Silent),
		}); err != nil {
			fmt.Println("连接mysql报错：", err.Error())
			panic(err)
		}
	} else if config.GConfig.DbDriver == "sqlserver" {
		dsn = "sqlserver://" + config.GConfig.SqlserverUser + ":" + config.GConfig.SqlserverPassword + "@" + config.GConfig.SqlserverHost + ":" + config.GConfig.SqlserverPort + "?database=" + config.GConfig.SqlserverName
		//dsn = fmt.Sprintf("server=%s;port=%d;database=%s;user id=%s;password=%s",host,port,database,user,password)
		//dsn = fmt.Sprintf("sqlserver://%s:%s@%s:%s?database=%s", config.G_config.SqlserverUser, config.G_config.SqlserverPassword, config.G_config.SqlserverHost, config.G_config.SqlserverPort, config.G_config.SqlserverName)
		if db, err = gorm.Open(sqlserver.Open(dsn), &gorm.Config{
			Logger: logger.Default.LogMode(logger.Info),
		}); err != nil {
			fmt.Println("连接sqlserver报错：", err.Error())
			panic(err)
		}
	} else {
		panic("未配置sql")
	}

	//使用插件
	db.Use(&plugin.SqlTracePlugin{})

	GDatabase = &DB{
		Db:  db,
		Dsn: dsn,
	}
	return
}
